﻿//"The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in
//compliance with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/

//Software distributed under the License is distributed on an "AS IS"
//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//License for the specific language governing rights and limitations
//under the License.

//The Original Code is TSharp.

//The Initial Developer of the Original Code is Mar3ek (http://mar3ek.wordpress.com).
//Portions created by Mar3ek are Copyright (C) 2010
//Mar3ek (http://mar3ek.wordpress.com). All Rights Reserved.

//Contributor(s): ______________________________________.

//Alternatively, the contents of this file may be used under the terms
//of the _____ license (the  "[___] License"), in which case the
//provisions of [______] License are applicable instead of those
//above.  If you wish to allow use of your version of this file only
//under the terms of the [____] License and not to allow others to use
//your version of this file under the MPL, indicate your decision by
//deleting  the provisions above and replace  them with the notice and
//other provisions required by the [___] License.  If you do not delete
//the provisions above, a recipient may use your version of this file
//under either the MPL or the [___] License."

using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace TSharp
{
    internal static class Globals
    {
        private static readonly TimeSpan TimeDiff;

        static Globals()
        {
            var request = (HttpWebRequest)WebRequest.Create(new Uri("https://api.twitter.com/1/help/test.xml"));
            request.Method = "HEAD";

            try
            {
                var response = request.GetResponse();
                var twitterTime = DateTime.Parse(response.Headers["Date"]);
                TimeDiff = DateTime.Now.Subtract(twitterTime);
            }
            catch (WebException)
            {
                TimeDiff = new TimeSpan();
            }
        }

        internal static TimeSpan TwitterTimeDifference
        {
            get { return TimeDiff; }
        }

        /// <summary>
        /// Creates a cryptographically strong nonce
        /// </summary>
        /// <returns>Nonce</returns>
        internal static string CreateNonce()
        {
            const string alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var sb = new StringBuilder();
            var random = new Random();

            for (var i = 0; i <= 24; i++)
            {
                var index = random.Next(alphanumeric.Length);
                sb.Append(alphanumeric[index]);
            }

            return sb.ToString();
        }

        /// <summary>
        /// Performs URL encoding in accordance with Twitter's URL encoding requirements
        /// </summary>
        /// <param name="stringToEscape">String to be URL encoded</param>
        /// <returns>URL encoded string</returns>
        internal static string ProperUrlEscape(string stringToEscape)
        {
            // URL encoding podľa Microsoftu
            var result = HttpUtility.UrlEncode(stringToEscape, Encoding.UTF8).Replace("+", "%20");

            // lower-case -> upper-case
            var hexRegex = new Regex("%[0-9a-f]{2}", RegexOptions.Compiled);
            var matches = hexRegex.Matches(result);

            result = matches.Cast<object>().Aggregate(result, (current, m) => current.Replace(m.ToString(), m.ToString().ToUpper()));

            // C# nekóduje (, ), $, !, * a "
            var notEncodedChars = new[] {"(", ")", "$", "!", "*", "\'"};

            result = notEncodedChars.Aggregate(result, (current, c) => current.Replace(c, String.Format("%{0}", ((int) Char.Parse(c)).ToString("X"))));

            // tilda nesmie byť zakódovaná
            result = result.Replace("%7E", "~");

            return result;
        }
    }
}
